package com.evanp.centre.good.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.evanp.centre.good.model.dto.*;
import com.evanp.centre.good.model.po.AxeType;
import com.evanp.centre.good.model.po.Good;
import com.evanp.centre.good.model.vo.AxeTypeBranch;
import com.evanp.centre.good.model.vo.GoodVo;
import com.evanp.centre.good.service.AxetypeService;
import com.evanp.centre.good.service.GoodImgService;
import com.evanp.centre.good.service.GoodService;
import com.evanp.centre.good.service.GoodUtilService;
import com.evanp.centre.util.ResBuilder;
import com.evanp.centre.util.StringUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/good")
public class GoodController {
    @Resource
    private GoodService goodService;
    @Resource
    private GoodImgService goodImgService;
    @Resource
    private AxetypeService axetypeService;
    @Resource
    private GoodUtilService goodUtilService;

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/GoodAdd"  method="POST">添加商品接口</a>
     * @Description 添加商品接口，接收商品信息和商品图片，需要验证登录和商家身份
     * @Param goodAddDto 新增商品DTO，包含商品名称，简介，单价，数量，uid等
     * @Param files 商品图片列表
     * @Return Result 封装的Result返回体，包含code,msg和data，code:400失败，200成功
     * */
    @SaCheckLogin
    @SaCheckRole("0")
    @PostMapping("/GoodAdd")
    public Map saveGood(GoodAddDto goodAddDto, @RequestParam("file") MultipartFile[] files) throws IOException {
        Map err = goodUtilService.check_publish(goodAddDto);
        if (err!=null) {
            return err;
        }
        Good good = new Good().inject_publish(goodAddDto);
        List<String> img_list = goodUtilService.upload_imglist(files);
        goodService.publish_one(good, img_list);
        return ResBuilder.ok("发布商品成功！");
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/displayedGood"  method="GET">获取未下架商品数接口</a>
     * @Description 获取未下架的商品数接口
     * @Return Map 返回一个Map，有一个键num，对应未下架的商品数量
     * */
    @GetMapping("/displayedGood")
    public Map getDisplayedGoodNum(){
        Map rs = new HashMap();
        Map option_sold = new HashMap();
        option_sold.put("gstate", 1);
        Map option_frozen = new HashMap();
        option_frozen.put("gstate", 0);
        int num = goodService.sel_count_options(option_sold)+goodService.sel_count_options(option_frozen);
        rs.put("num",num);
        return rs;
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/getGoodByGid">根据商品id查询接口</a>
     * @Description 根据gid查询商品接口，接收1个路径参数
     * @Param gid 商品id
     * @Return Result code:404 失败，200成功
     * */
    @RequestMapping("/getGoodByGid")
    public Map queryGoodByGid(@RequestParam String gid){

        GoodVo g = goodService.sel_goodvo_by_gid(gid);
        if(g!=null){
//            List<String> url_list = goodImgService.sel_url_by_gid(gid);
//            g.setGimgpath(url_list);
            return ResBuilder.ok("查询成功");
        }else{
            return ResBuilder.notFound("查询失败");
        }
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/getAllGoods">获取所有商品列表接口</a>
     * @Description 获取所有商品列表
     * @Return Result
     * */
    @RequestMapping("/getAllGoods")
    public Map query_all_good(){
        List<GoodVo> glist = goodService.sel_all_to_goodvo();

//        /*设置图片链接*/
//        for (GoodVo g : glist) {
//            String gid = g.getGid();
//            List<String> url_list = goodImgService.sel_url_by_gid(gid);
//            g.setGimgpath(url_list);
//        }
        return ResBuilder.ok("查询成功", 0, glist);
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/goodpage?pageNum=?&pageSize=?&keyword=?&Type=?&level=?"  method="GET">分页查询商品接口</a>
     * @Description 分页查询商品接口，接收5个路径参数，3个必填参数，和2个选填参数
     * @Param pageNum 必填，页数，第几页
     * @Param pageSize 必填，每页条数
     * @Param keyword 选填，关键词，用于根据商品名字搜索筛选商品
     * @Param Type 必填，查询类型，允许两个值：'displayed'和'all'，分别代表上架的和所有的
     * @Param level 选填，商品类别，用于根据类别筛选商品，一级分类和二级分类都可匹配
     * @Return Result code:200成功，400失败,data内置Map，包含键glist和gtotal，前者是商品列表，后者是符合条件的总商品数目
     * */
    @GetMapping("/goodpage")
    public Map findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam(required = false) String keyword, @RequestParam String Type,@RequestParam(defaultValue = "0") Integer level){
        GoodPageQueryDto goodPageQueryDto = new GoodPageQueryDto(
            pageNum,
            pageSize,
            keyword,
            Type,
            level
        );
        Map err = goodUtilService.check_query_good_page(goodPageQueryDto);
        if (err != null) {
            return err;
        }

        Map res = new HashMap();
        List<GoodVo> glist = goodService.query_good_page_dynamic(pageNum,pageSize,keyword,level,Type);
        int gtotal = goodService.sel_count_page(keyword,Type);
        res.put("glist",glist);
        res.put("gtotal",gtotal);

        if(glist.size()!=0){
            return ResBuilder.ok("获取成功", 0, res);
        }else{
            if(!StringUtil.is_blank(keyword)){
                return ResBuilder.ok("当前没有商品");
            }else{
                return ResBuilder.fail("没有相关的商品");
            }
        }
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/updateGoods"  method="POST">更改商品状态接口</a>
     * @Description 更改商品状态接口，接收body
     * @Param goodUpdateDto 更新商品状态DTO，包含gid和gstate（新状态）
     * @Return Result code:400 失败，200成功
     * */
    @PostMapping("/updateGoods")
    public Map updateGood(@RequestBody GoodStateUpdateDto goodStateUpdateDto){
        Map err = goodUtilService.check_upd_state(goodStateUpdateDto);
        if (err!=null){
            return err;
        }

        goodService.upd_state_by_gid(goodStateUpdateDto.getGstate(),goodStateUpdateDto.getGid());
        return ResBuilder.ok("商品修改成功！");
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/increaseGoodNum?gid=?&num=?">增加某商品库存接口</a>
     * @Description 增加某商品库存接口，接收2个路径参数
     * @Param gid 商品id
     * @Param num 变动数量
     * @Return Result code:200成功,gQuantity:更新后的储量
     * */
    @RequestMapping("/increaseGoodNum")
    public Map increaseGoodNum(@RequestParam String gid,@RequestParam int num){
        goodService.add_store_by_gid(num,gid);
        int storage = goodService.sel_store_by_gid(gid);
        Map rs = new HashMap();
        rs.put("code","200");
        rs.put("msg","库存已增加");
        rs.put("gstorage",storage);
        return rs;
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/increaseGoodNum?gid=?&num=?">减少某商品库存接口</a>
     * @Description 减少某商品库存接口，接收2个路径参数，会检查库存是否够扣这么多
     * @Param gid 商品id
     * @Param num 变动数量
     * @Return Result code:200成功，400失败,gQuantity:更新后的储量
     * */
    @RequestMapping("/decreaseGoodNum")
    public Map decreaseGoodNum(@RequestParam String gid,@RequestParam int num){
        Map rs = new HashMap();
        int storage = goodService.sel_store_by_gid(gid);
        int delta = num;
        if(storage-delta<0){
            rs.put("code","400");
            rs.put("msg","库存没有那么多");
            rs.put("gstorage",storage);
        }else {
            goodService.cut_store_by_gid(delta, gid);
            rs.put("code","200");
            rs.put("msg","库存已减少");
            rs.put("gstorage",storage-delta);
        }
        return rs;
    }


    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/axeTypes"  method="GET">获取全部商品分类接口</a>
     * @Description 获取全部商品分类
     * @Return Result code:200成功
     * */
    @GetMapping("/axeTypes")
    public Map getAxeTypesAll(){
        List<AxeTypeBranch> axeTypeBranches = axetypeService.sel_axetype_branches();
        return ResBuilder.ok("获取成功", 0, axeTypeBranches);
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/axeType"  method="PUT">添加商品分类接口</a>
     * @Description 添加商品分类接口，接收3个路径参数，2个必填，1个选填
     * @Param name 必填，分类名字，非空，不可为其他/其它，不可重名
     * @Param level 必填，该分类所属的级别，当前Version只允许1或2
     * @Param dadId 选填，如果该分类有上级分类就要填，这样设计可以直接拓展成多级分类
     * @Return Result code:200成功，400失败
     * */
    @PutMapping("/axeType")
    public Map addAxeType(@RequestParam String name,@RequestParam int level,@RequestParam(required = false,defaultValue = "0") int dadId){
        AxetypeAddDto axetypeAddDto = new AxetypeAddDto(name,level,dadId);
        Map err = goodUtilService.check_add_axetype(axetypeAddDto);
        if (err != null) {
            return err;
        }
        AxeType axeType = new AxeType();
        axeType.setName(name);axeType.setLevel(level);axeType.setDadId(dadId);
        axetypeService.ins_one(axeType);
        axeType = axetypeService.sel_all_by_name(name);
        if(level==1) {  //如果是一级分类，为其创建名为其他的子分类
            AxeType axeType2 = new AxeType();
            axeType2.setName("其他");axeType2.setLevel(level-1);axeType2.setDadId(axeType.getId());
            axetypeService.ins_one(axeType2);
        }
        return ResBuilder.ok("添加成功", 0, axeType);
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/axeType  method="DELETE"">删除商品分类接口</a>
     * @Description 删除商品分类接口，接收1个路径参数，基础分类收到保护不允许删除
     * @Param id 必填，分类的id
     * @Return Result code:200成功，400失败
     * */
    @DeleteMapping("/axeType")
    public Map delAxeType(@RequestParam int id){
        Map err = goodUtilService.check_del_axetype(id);
        if (err != null) {
            return err;
        }
        axetypeService.del_by_id(id);
        return ResBuilder.ok("删除成功");
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/axeType" method="POST">修改分类名字接口</a>
     * @Description 修改分类名字接口，接收2个路径参数，基础分类收到保护不允许修改
     * @Param id 必填，分类的id
     * @Param name 分类的新名字
     * @Return Result code:200成功，400失败
     * */
    @PostMapping("/axeType")
    public Map updAxeType(@RequestParam int id,@RequestParam String name){
        AxetypeNameUpdDto axetypeNameUpdDto = new AxetypeNameUpdDto(id, name);
        Map err = goodUtilService.check_upd_axetype_name(axetypeNameUpdDto);
        if (err != null) {
            return err;
        }

        axetypeService.upd_name_by_id(name,id);
        AxeType axeType_after = axetypeService.sel_all_by_id(id);
        return ResBuilder.ok("修改成功", 0, axeType_after);
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/GoodType" method="POST">修改商品的分类归属接口</a>
     * @Description 修改商品的分类归属接口，接收body
     * @Param goodTypeUpdDto 必填，商品分类修改DTO
     * @Return Result code:200成功，400失败
     * */
    @PostMapping("/GoodType")
    public Map updGoodType(@RequestBody GoodTypeUpdDto goodTypeUpdDto){
        Map err = goodUtilService.check_upd_good_type(goodTypeUpdDto);
        if (err != null) {
            return err;
        }
        int level1 = goodTypeUpdDto.getLevel1();
        int level2 = goodTypeUpdDto.getLevel2();
        Map data = new HashMap();
        data.put("level1",level1);
        data.put("level1name",axetypeService.sel_all_by_id(level1));
        data.put("level2",level2);
        data.put("level2name",axetypeService.sel_all_by_id(level2));

        return ResBuilder.ok("修改成功", 0, data);
    }

    @PutMapping("/price/{gid}")
    public Map upd_gprice_by_gid_by_seller(@PathVariable String gid, @RequestParam(name = "gprice") String gprice_given) {
        return goodService.upd_gprice_by_gid_by_seller(gid,gprice_given);
    }

    @GetMapping("/price/{gid}")
    public Map get_history_price_by_gid(@PathVariable String gid) {
        return goodService.sel_history_prices_by_gid(gid);
    }

}
